import qs from 'qs';
import { saveAs } from 'file-saver';
import type { ResponseCustom } from '@sa/axios/type';
import { request } from '../request';

interface PostFormParams {
  url: string;
  data?: any;
  method?: 'get' | 'post' | 'put' | 'delete';
}

type Custom = Extract<ResponseCustom, 'custom'>;

/**
 * post FormData
 *
 * @param url 请求地址
 * @param data 请求数据
 * @returns request Promise
 */
export function fetchPostForm<R>({ url = '', data = {} }: PostFormParams) {
  return request<R>({
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    transformRequest: [originData => qs.stringify(originData)],
    url,
    method: 'post',
    data
  });
}

export async function fetchDownloadFile(
  { url = '', data = {}, method = 'get' }: PostFormParams,
  filename: string = 'file'
) {
  const result = await request<Blob | null, 'blob', Custom>({
    url,
    method,
    responseType: 'blob',
    data
  });
  if (!result) {
    window.$message?.warning('文件下载失败');
  } else {
    saveAs(new Blob([result]), filename);
  }
}
